#!/bin/bash

# Import configuration files
source ./config.cfg



# Function definitions

# Function to unzip 
unzip_package_if_not_exists() {
    local ZIP_FILE=$1
    local SDK_DIR=$2
    local TARGET_DIR=$3

    echo "Checking if '$ZIP_FILE' exists..."
    if [ -f "$ZIP_FILE" ]; then
        echo "Found '$ZIP_FILE' package, checking existing files..."

        if [ ! -f "$SDK_DIR/$TARGET_DIR" ]; then
            echo "No existing files found, unzipping..."
            unzip "$ZIP_FILE" -d "$SDK_DIR"
        else
            echo "File already exists, skipping unzip..."
        fi
    else
        echo "Error: '$ZIP_FILE' not found. Exiting..."
        exit 1
    fi
}



# Configure the SDK insatllation environment

# Update package list
echo "Upddating pack list..."
sudo apt update

# Install required packages
echo "Installing packages..."
sudo apt-get install -y git ssh make gcc libssl-dev liblz4-tool \
expect g++ patchelf chrpath gawk texinfo chrpath diffstat binfmt-support \
qemu-user-static live-build bison flex fakeroot cmake gcc-multilib g++-multilib \
unzip device-tree-compiler libncurses-dev

# Install python packages
echo "Installing python packages..."
sudo apt install python3-pip
sudo pip install python-pip pyelftools
sudo apt install python2

# Configure python environment
echo "Configuring python environment..."
sudo ln -s /usr/bin/python3.10 /usr/bin/python

# Complete
echo "Installation complete."



# Set the path of the SDK
SDK_DIR="$SDK_DIR_PRE/Lemon-3588-SDK-Linux-V1.0"
SUBMODULES_REPO="https://gitee.com/HaozhongXu/lemon-3588-sdk-linux.git"
DEBIAN_ZIP_FILE="$SCRIPT_DIR/debian.zip"
EXTERNAL_ZIP_FILE="$SCRIPT_DIR/external.zip"
PREBUILTS_ZIP_FILE="$SCRIPT_DIR/prebuilts.zip"
UBUNTU_ZIP_FILE="$SCRIPT_DIR/ubuntu.zip"

# Check if the SDK directory exists
if [ ! -d "$SDK_DIR" ]; then
    echo "Cloning SDK repository..."
    git clone --recurse-submodules "$SUBMODULES_REPO" "$SDK_DIR"
else
    echo "SDK directory already exists. Pulling latest changes..."
    cd "$SDK_DIR"
    git pull origin main
    git submodule update --recursive --remote
fi

echo "SDK source code download complete."

# Unzip and configure the offline installation package
echo "Unzipping offline installation package..."
echo "Checking the corresponding offline zip packages..."

# Check debian.zip
unzip_package_if_not_exists "$DEBIAN_ZIP_FILE" "$SDK_DIR" "debian"

# Check external.zip
unzip_package_if_not_exists "$EXTERNAL_ZIP_FILE" "$SDK_DIR" "external"

# Check prebuilts.zip
unzip_package_if_not_exists "$PREBUILTS_ZIP_FILE" "$SDK_DIR" "prebuilts"

# Check ubuntu.zip
unzip_package_if_not_exists "$UBUNTU_ZIP_FILE" "$SDK_DIR" "ubuntu"

echo "Offline installation package unzipped."


# Create the target links
ln -s "$SDK_DIR/device/rockchip/rk3588" "$SDK_DIR/device/rockchip/.target_product" 

# Complete
echo "SDK setup complete."
